﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ProgNetComponentsDx.Forms;
using BuildHelper.Kontakt;
using ProgNetComponentsDx.Options;
using ProgNetComponentsDx.Browsers;
using ProgNetComponents.Classes;
using ProgNetComponents.MDI;
using DevExpress.XtraBars.Alerter;
using System.Diagnostics;
using BuildHelper.Setup.Brancze;
using BuildHelper.Work.GUI;
using System.Runtime.InteropServices;
using DevExpress.XtraBars;
using ProgNetComponents.Utils;
using DevExpress.XtraEditors;
using ProgNetComponents.Data.SqlCe;
using System.Threading.Tasks;
using BuildHelper.Setup.ProcedurySql.CustomBrowsers;

namespace BuildHelper
{
    public partial class FormMain : HideToTrayForm
    {
        private object BrowserCancel = new object();
        private string OldGlobalDrive;
        private Dictionary<Type, int> imageIndexes = new Dictionary<Type, int>();
        private void RegisterForms()
        {
            RegisterForm<BudowanieGui>(93);
            RegisterForm<Work.JAVA.BudowanieJavy>(94);
            RegisterForm<Setup.Srodowiska.FormSrodowiska>(83);
            RegisterForm<Setup.BazyDanych.FormBazyDanych>(17);
            RegisterForm<Setup.Serwery.SerweryForm>(58);
            RegisterForm<Setup.Pliki.FormPliki>(74);
            RegisterForm<Setup.Pliki.FormPlikiRecord>(74);
            RegisterForm<Setup.Pliki.FormPliki>(74);
            RegisterForm<Setup.Apps.FormProjekty>(102);
            RegisterForm<Setup.Brancze.FormBrancz>(107);
            RegisterForm<Setup.Konfigi.FormKonfigi>(101);
            RegisterForm<Setup.Opcje.FormOpcje>(13);
            RegisterForm<Work.Tortoise.TortoiseForm>(100);
            RegisterForm<Work.OperacjeNaPlikach.OperacjeNaPlikachForm>(56);
            RegisterForm<Scheduler.FormMultiTask>(39);
            RegisterForm<Work.Tools.DBUtilsForm>(103);
            RegisterForm<BuildHelper.Setup.Faktury.Bills.FormBills>(53);
            RegisterForm<FormCustomBrowserAll>(bbiCustomBrowser.ImageIndex);
            RegisterForm<Work.Tools.ScriptCompare.CompareForm>(bbiScriptCompare.ImageIndex);
        }
        private void RegisterForm<T>(int i)
        {
            if (!imageIndexes.ContainsKey(typeof(T)))
            {
                imageIndexes.Add(typeof(T), i);
            }
        }
       
        #region Alert
        public static Bitmap ErrorImg;
        public static Bitmap InfoImg;
        public static Bitmap WarnImg;

        private static AlertControl alert;
        private static bool ChowajAlerty = true;
        private static bool NieChowajErrorow = false;
        private static bool NieChowajWarningow = false;
        public class AlertInfo
        {
            public AlertInfo(bool shouldStay = false, object id=null)
            {
                Centerid = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Alerty.WyswietlajNaSrodku);
                ShouldStay = shouldStay;
                Id = id;
            }

            public bool ShouldStay
            {
                get;
                set;
            }
            public bool Centerid
            {
                get;
                set;
            }
            public object Id
            {
                get;
                set;
            }
        }

        public static void UpdateAlertText(object id, string text)
        {
            if (FormMain.Instance.InvokeRequired)
            {
                FormMain.Instance.Invoke(new Action<object, string>(UpdateAlertText), id, text);
                return;
            }
            AlertForm[] forms = alert.AlertFormList.ToArray();
            if (forms != null && forms.Length > 0)
            {
                foreach (AlertForm f in forms)
                {
                    try
                    {
                        if (f.AlertInfo != null && f.AlertInfo.Tag != null && f.AlertInfo.Tag is AlertInfo)
                        {
                            if ((f.AlertInfo.Tag as AlertInfo).Id.IsTheSame(id))
                            {
                                f.AlertInfo.Text = text;
                                f.Refresh();
                            }
                        }
                    }
                    catch { }
                }
            }
        }
        private static void ShowAlert(string text, bool shouldStay, Image image)
        {
            ShowAlert(text, image, new AlertInfo(shouldStay));
        }
        private static void ShowAlert(string text, bool shouldStay, bool centerid, Image image)
        {
            AlertInfo a = new AlertInfo();
            a.ShouldStay = shouldStay;
            a.Centerid = centerid;
            ShowAlert(text, image, a);
        }
        public static void ShowAlert(string text, Image image, AlertInfo info)
        {
            if (Instance.InvokeRequired)
                Instance.Invoke(new Action<string, Image, AlertInfo>(ShowAlert), text, image, info);
            else
            {
                string title = "";
                string opt = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Rozne_Group.Alerty.DodajCzas);
                switch (opt)
                {
                    case "N":
                        break;
                    case "CT":
                        title = DateTime.Now.ToString("T");
                        break;
                    case "CDT":
                        title = DateTime.Now.ToString("G");
                        break;
                    case "CWT":
                        text = DateTime.Now.ToString("T") + "\n" + text;
                        break;
                    case "CDWT":
                        text = DateTime.Now.ToString("G") + "\n" + text;
                        break;
                }
                alert.Show(Instance, title, text, "", image, info);
            }
        }
        public static void ShowAlert(string text, AlertType type, AlertInfo info = null)
        {
            Image img = null;
            switch (type)
            {
                case AlertType.Error:
                    img = ErrorImg;
                    break;
                case AlertType.Info:
                    img = InfoImg;
                    break;
                case AlertType.Warn:
                    img = WarnImg;
                    break;
            }
            if (info == null)
                info = new AlertInfo();
            ShowAlert(text, img, info);
        }

        public static void ShowErrorAlert(string text, string id = null)
        {
            AlertInfo info = new AlertInfo();
            info.ShouldStay = NieChowajErrorow || !ChowajAlerty;
            info.Id = id;
            ShowAlert(text, ErrorImg, info);
        }
        public static void ShowErrorAlertDontHide(string text)
        {
            ShowAlert(text, true, ErrorImg);
        }

        public static void ShowInfoAlert(string text, string id = null)
        {
            AlertInfo info = new AlertInfo();
            info.ShouldStay = !ChowajAlerty;
            info.Id = id;
            ShowAlert(text, InfoImg, info);
        }
        public static void ShowWarningAlert(string text, string id = null)
        {
            AlertInfo info = new AlertInfo();
            info.ShouldStay = NieChowajWarningow || !ChowajAlerty;
            info.Id = id;
            ShowAlert(text, WarnImg, info);
        }

        private void alert_FormLoad(object sender, AlertFormLoadEventArgs e)
        {
            AlertInfo a = e.AlertForm.AlertInfo.Tag as AlertInfo;
            if (a != null)
            {
                if (a.ShouldStay)
                    e.Buttons.PinButton.SetDown(true);
                if (a.Centerid)
                {
                    int left = Screen.PrimaryScreen.WorkingArea.Width - e.AlertForm.Width;
                    int top = Screen.PrimaryScreen.WorkingArea.Height - e.AlertForm.Height;
                    e.AlertForm.Location = new Point(left / 2, top / 2);
                }
            }
        }
        private void CloseAllAlerts()
        {
            AlertForm[] forms = alert.AlertFormList.ToArray();
            if (forms != null && forms.Length > 0)
            {
                foreach (AlertForm f in forms)
                {
                    try
                    {
                        f.Close();
                    }
                    catch { }
                }
            }
        }
        public static void CloseAlertById(object id)
        {
            if (Instance.InvokeRequired)
            {
                Instance.Invoke(new Action<object>(CloseAlertById), id);
                return;
            }
            AlertForm[] forms = alert.AlertFormList.ToArray();
            if (forms != null && forms.Length > 0)
            {
                foreach (AlertForm f in forms)
                {
                    try
                    {
                       if (f.AlertInfo != null && f.AlertInfo.Tag != null && f.AlertInfo.Tag is AlertInfo)
                        {
                            if ((f.AlertInfo.Tag as AlertInfo).Id.IsTheSame(id))
                                f.Close();
                        }
                    }
                    catch { }
                }
            }
        }
        public static bool IsAlertShown(object id)
        {
            if (Instance.InvokeRequired)
            {
                return Instance.Invoke(new Func<object, bool>(IsAlertShown), id).AsBool();
            }
            AlertForm[] forms = alert.AlertFormList.ToArray();
            if (forms != null && forms.Length > 0)
            {
                foreach (AlertForm f in forms)
                {
                    try
                    {
                        if (f.AlertInfo != null && f.AlertInfo.Tag != null && f.AlertInfo.Tag is AlertInfo)
                        {
                            if ((f.AlertInfo.Tag as AlertInfo).Id.IsTheSame(id))
                                return true;
                        }
                    }
                    catch { }
                }
            }
            return false;
        }
        #endregion

        internal static FormMain Instance
        {
            get;
            set;
        }
        private Process substProcess = null;
        private Process DbChangeProcess = null;

        public FormMain()
        {
            InitializeComponent();
            if (!this.IsDesignMode())
            {
                RegisterForms();

                this.Text = "BuildHelper [v. " + Application.ProductVersion + "]";
                GlobalTools.ServerTools.SearchDB();

                xtraTabbedMdiManager1.SetMinTabSize(100);

                Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
                InfoImg = new Bitmap(SystemIcons.Information.AsImage());
                ErrorImg = new Bitmap(SystemIcons.Error.AsImage());
                WarnImg = new Bitmap(SystemIcons.Warning.AsImage());

                InfoImg.MakeTransparent(InfoImg.GetPixel(1,1));
                ErrorImg.MakeTransparent(ErrorImg.GetPixel(1,1));
                WarnImg.MakeTransparent(WarnImg.GetPixel(1,1));

                xtraTabbedMdiManager1.AddTabMenu();
                OldGlobalDrive = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Brancze.ActiveBranczDrive);
                beiDefServer.EditValue = OptionCache.GetOptionValue(Init.InitFormOptionNames.Rozne_Group.StatusBar.DefServer);
                
                
                Setup.Brancze.BranczeTools.ActiveBranchChanged += new EventHandler(Tools_ActiveBranchChanged);
                DataTable dt = BrowserCache.GetBrowserData(Init.InitFormBrowserNames.Setup.Brancze);
                if (dt != null)
                {
                    substProcess = GlobalTools.CreateCMDProcess(substProcessData);
                    foreach (DataRow r in dt.Rows)
                    {
                        if (r["STP_BR_DRIVE"].IsNotNull())
                            Setup.Brancze.BranczeTools.SubstDrive(r["STP_BR_DRIVE"].AsString(), r["STP_BR_KATALOG"].AsString());
                    }
                    substProcess.Execute("echo exit");
                }
                OptionCache.OptionChanged += new OptionChangedEventHandler(OptionCache_OptionChanged);
                OptionCache_OptionChanged(null);

                ChowajAlerty = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Alerty.ChowajAutomatycznie);
                NieChowajErrorow = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Alerty.NieChowajErrorow);
                NieChowajWarningow = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Alerty.NieChowajWarningow);
                
               
                Instance = this;
                KontaktTools.RunKontakty();
                bbiResetSerwera.Visibility =
                    bbiStopSerwer.Visibility = (Kontakt.KontaktTools.IsServer ? BarItemVisibility.Always : BarItemVisibility.Never);
                
                if (Program.IsArgPresent(Argumenty.NoContact))
                    bbiKontakt.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

                bbiWsCaller.Visibility = Program.IsDebug ? BarItemVisibility.Always : BarItemVisibility.Never;


                alert = this.alertControl1;
                alert.AutoFormDelay = 1000 * OptionCache.GetOptionValue(Init.InitFormOptionNames.Rozne_Group.Alerty.CzasAlertu).AsInt(1);

                Setup.Brancze.BranczeTools.ActiveBranch = GetActiveBrancz();
                
                bbiUpdateCurrentBrancz.Caption = "Aktualny Brancz";
                if (Setup.Brancze.BranczeTools.ActiveBranch.IsNotNull())
                    bbiUpdateCurrentBrancz.Caption += " (" + Setup.Brancze.BranczeTools.ActiveBranch + ")";

                object dw = OptionCache.GetOptionValue(Init.InitFormOptionNames.Niewidoczne.OstatniDzienWyjscia);
                if (dw != null && dw is DateTime)
                {
                    if ((dw.AsDateTime(DateTime.MinValue)) == DateTime.Today)
                    {
                        int tw = OptionCache.GetOptionValue(Init.InitFormOptionNames.Niewidoczne.OstatniCzasWyjscia).AsInt(0);
                        if (tw > 0)
                        {
                            setFromGodzina = true;
                            beiOtisGodzinaWyjscia.EditValue = tw;
                        }
                    }
                }

                if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Otis.AutomatycznieOdliczaj) &&
                OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Otis.PokazPasekOtisa))
                {
                    GlobalTools.OtisTools.SprawdzOtis(true);
                }
            }
        }
        private static string GetActiveBrancz()
        {
            string NSDIR = Environment.GetEnvironmentVariable("NSDIR", EnvironmentVariableTarget.Machine);
            NSDIR = NSDIR.AsString().TrimEnd('\\');

            DataTable dt = new DataTable();
            NSDIR = NSDIR.XReplace("\\\\nd_src$", "");
            string katalog = "";
            if (NSDIR.Length == 2)
            {
                BrowserCache.RefreshCacheForBrowser(Init.InitFormBrowserNames.Statyczne.SubstedDrives);
                DataRow r = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Statyczne.SubstedDrives, NSDIR.SubstringSafe(0, 1));
                if (r != null)
                    katalog = r["KATALOG"].AsString();
            }
            else
            {
                katalog = NSDIR;
            }
            string sysAB = "";
            SqlCeDataManager m = Manager;
            m.FillTable(dt, "SELECT STP_BR_NAZWA FROM STP_BRANCZE WHERE STP_BR_KATALOG = " + katalog.EscapeSql());
            m.Dispose();

            if (dt.Rows.Count == 1)
                sysAB = dt.Rows[0]["STP_BR_NAZWA"].AsString();
            string lastOAB = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Niewidoczne.OstatniBrancz);
            string opt = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Brancze.SkadAktywnyBrancz);
            string br = "";
            switch (opt)
            {
                case "O":
                    if (lastOAB.IsNotNull())
                        return lastOAB;
                    break;
                case "S":
                    if (sysAB.IsNotNull())
                        return sysAB;
                    break;
                case "P":
                    if (lastOAB.IsNotNull() && sysAB.IsNotNull())
                    {
                        if (lastOAB != sysAB)
                        {
                            string msg = "Źródło aktywnego brancza:" + Constants.NewLineLinux +
                                "System: " + sysAB + Constants.NewLineLinux +
                                "Ostatni w aplikacji: " + lastOAB;
                            List<System.DxFormExt.DialogResultText> l = new List<DxFormExt.DialogResultText>();
                            l.Add(new DxFormExt.DialogResultText(DialogResult.Yes, "System"));
                            l.Add(new DxFormExt.DialogResultText(DialogResult.No, "Ostatni"));
                            DialogResult dlg = FormMain.Instance.ShowDxDialog(msg, "Aktywny Brancz", MessageBoxButtons.YesNo, MessageBoxIcon.Question, l.ToArray());
                            if (dlg == DialogResult.Yes)
                                br = sysAB;
                            else if (dlg == DialogResult.No)
                                br = lastOAB;
                        }
                        return br;
                    }
                    break;
            }

            if (lastOAB.IsNotNull())
            {
                FormMain.ShowAlert("Aktywny brancz ustawiony na podstawie ostatniego brancza.", FormMain.WarnImg, new FormMain.AlertInfo(true));
                return lastOAB;
            }
            if (sysAB.IsNotNull())
            {
                FormMain.ShowAlert("Aktywny brancz ustawiony na podstawie ustawień systemu.", FormMain.WarnImg, new FormMain.AlertInfo(true));
                return sysAB;
            }
            return "";
        }
        private static SqlCeDataManager Manager
        {
            get
            {
                SqlCeDataManager _Manager;
                _Manager = new SqlCeDataManager();
                _Manager.AutoLogExceptions = true;
                return _Manager;
            }
        }

        DateTime lastDay = DateTime.Today;

        void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
        {
            bool odliczaj = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Otis.AutomatycznieOdliczaj);

            if (lastDay != DateTime.Today)
            {
                lockOtis = true;
                beiOtisCzasPrzyjscia.EditValue = null;
                beiOtisPozadany.EditValue = null;
                beiOtisGodzinaWyjscia.EditValue = null;
                beiOtisPozostalo.EditValue = null;
                lockOtis = false;

                lastDay = DateTime.Today;
                beiOtisPozadany.EditValue = "";

            }
            else
            {
                odliczaj = false;
            }
            
            if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Otis.PokazPasekOtisa))
            {
                Task t = Task.Factory.StartNew(() =>
                {
                    for (int i = 0; i < 100; i++)
                    {
                        System.Threading.Thread.Sleep(500);
                        if (Program.IsExit)
                            return;
                    }
                    GlobalTools.OtisTools.SprawdzOtis(odliczaj);
                });
            }
        }
        private void PrepareMenuItems(BarItemLinkCollection links)
        {
            
            int size = commonImageCollectionFull1.ImageSize.Width;
            foreach (BarItemLink item in links)
            {
                if (item.Item != null && item.Item.Glyph != null)
                {
                    if (item.Item.Glyph.Width > size)
                    {
                        item.Item.Glyph = item.Item.Glyph.ResizeImage(size, size);
                    }
                }
                if (item.Item is BarSubItem)
                    PrepareMenuItems((item.Item as BarSubItem).ItemLinks);
            }
        }
        private void substProcessData(object sender, DataReceivedEventArgs e)
        {
            if (e.Data.AsString() == "exit")
            {
                try
                {
                    if (substProcess != null)
                    {
                        substProcess.CallExit();
                        //substProcess.WaitForExit();
                        substProcess.KillProcessTree();
                        substProcess.Dispose();
                    }
                }
                catch { }
                substProcess = null;
            }
        }

        #region override
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            foreach (BarItem x in barManager1.Items)
            {
                if (x.Hint.IsNullOrEmpty())
                    x.Hint = x.Description;
            }

            PrepareMenuItems(bar2.ItemLinks);

            this.xtraTabbedMdiManager1.MultiLine = DevExpress.Utils.DefaultBoolean.True;
            this.xtraTabbedMdiManager1.HeaderAutoFill = DevExpress.Utils.DefaultBoolean.False;

            if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Uruchamianie.RunInTray))
                HideToTray();
            else
                ShowFromTray();

            string str = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Rozne_Group.Uruchamianie.RunMode);
            string[] parts;

            switch (str)
            {
                case "W":
                    parts = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Rozne_Group.Uruchamianie.WybraneFormy).Split('|');
                    if (parts.Contains(GlobalTools.WybraneFormy.BazyDanych))
                        mdiHelper.GetMdiChild<Setup.BazyDanych.FormBazyDanych>();
                    if (parts.Contains(GlobalTools.WybraneFormy.Srodowiska))
                        mdiHelper.GetMdiChild<Setup.Srodowiska.FormSrodowiska>();
                    if(parts.Contains(GlobalTools.WybraneFormy.BudowanieGui))
                        mdiHelper.GetMdiChild<Work.GUI.BudowanieGui>();
                    if (parts.Contains(GlobalTools.WybraneFormy.BudowanieJavy))
                        mdiHelper.GetMdiChild<Work.JAVA.BudowanieJavy>();
                    if (parts.Contains(GlobalTools.WybraneFormy.TortoiseSvn))
                        mdiHelper.GetMdiChild<Work.Tortoise.TortoiseForm>();
                    if (parts.Contains(GlobalTools.WybraneFormy.OperacjeNaPlikach))
                        mdiHelper.GetMdiChild<Work.OperacjeNaPlikach.OperacjeNaPlikachForm>();
                    if (parts.Contains(GlobalTools.WybraneFormy.Generator))
                        mdiHelper.GetMdiChild<Work.Tools.GeneratorForm>();
                    break;
                case "O":
                    mdiHelper.OpenFormsFromString(OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Rozne_Group.Uruchamianie.OtwarteFormy));
                    break;
            }
            mdiHelper.GetMdiChildFull<Scheduler.SchedulerForm>(MdiOptions.DefaultNoShow);
            Work.Short.ShortForm.ShowByDefault();
            
        }
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.ApplicationExitCall ||
            e.CloseReason == CloseReason.TaskManagerClosing ||
            e.CloseReason == CloseReason.WindowsShutDown)
            {
                Program.IsExit = true;
            }
            e.Cancel = false;
            if (!Program.IsExit)
            {
                if (this.ShowDxYNQuestionDialog("Czy napewno chcesz zamknąć aplikację?") == System.Windows.Forms.DialogResult.No)
                    e.Cancel = true;
            }

            if (!e.Cancel && !Program.IsExit)
            {
                BuildHelper.Work.Short.ShortForm.CloseInstance();

                List<IDataForm> changedForms = new List<IDataForm>();
                if (this.MdiChildren != null && MdiChildren.Length > 0)
                {
                    foreach (Form f in MdiChildren)
                    {
                        if (f is IDataForm)
                        {
                            if ((f as IDataForm).HasChanges)
                            {
                                changedForms.Add(f as IDataForm);
                            }
                        }
                    }
                }
                if (changedForms.Count > 0)
                {
                    string msg = "Wykryto nie zapisane zmiany:";
                    foreach (IDataForm i in changedForms)
                    {
                        msg = msg.AppendLine(i.Text.Replace("*", ""));
                    }
                    msg = msg.AppendLine("Chcesz je zapisać?");
                    DialogResult dlg = this.ShowDxYNCQuestionDialog(msg);

                    switch (dlg)
                    {
                        case System.Windows.Forms.DialogResult.Cancel:
                            e.Cancel = true;
                            break;
                        case System.Windows.Forms.DialogResult.No:
                            break;
                        case System.Windows.Forms.DialogResult.Yes:
                            foreach (IDataForm i in changedForms)
                            {
                                if (i.ValidateAll())
                                {
                                    if (!i.Save())
                                    {
                                        this.ShowDxErrorDialog("Błąd zapisu!");
                                        e.Cancel = true;
                                    }
                                }
                                else
                                {
                                    this.ShowDxWarningDialog("Błąd validacji.");
                                    e.Cancel = true;
                                }
                                if (e.Cancel)
                                {
                                    this.ActivateMdiChild(i as Form);
                                    break;
                                }
                            }
                            break;
                    }
                }
            }

            if (e.Cancel)
                Program.IsExit = false;
            else
                ProgNetComponentsDx.Layout.LayoutProvider.SaveAllLayouts();

            base.OnFormClosing(e);
            string str = mdiHelper.GetOpenedFormsString();
            OptionCache.SetOptionValue(Init.InitFormOptionNames.Rozne_Group.Uruchamianie.OtwarteFormy, str, true);
        }
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            Program.IsExit = true;
            try
            {
                object tw = null;
                object dw = null;
                if (beiOtisGodzinaWyjscia.EditValue.IsNotNull() && beiOtisGodzinaWyjscia.EditValue.AsInt() > 0)
                {
                    tw = beiOtisGodzinaWyjscia.EditValue.AsInt();
                    dw = DateTime.Today;
                }
                OptionCache.SetOptionValue(Init.InitFormOptionNames.Niewidoczne.OstatniCzasWyjscia, tw);
                OptionCache.SetOptionValue(Init.InitFormOptionNames.Niewidoczne.OstatniDzienWyjscia, dw);
                OptionCache.SaveOptions();
            }
            catch { }
            try
            {
                ProgNetComponentsDx.Layout.LayoutGrabber.Instance.SaveLayouts();
            }
            catch {  }
            
            base.OnFormClosed(e);
        }
        protected override void OnActivated(EventArgs e)
        {
            base.OnActivated(e);
            if (beiOtisCzasPrzyjscia.EditValue.IsNull() && lastDay != DateTime.Today &&
                OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Otis.PokazPasekOtisa))
            {
                GlobalTools.OtisTools.SprawdzOtis(false);
            }
            else if(OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Otis.PokazPasekOtisa) 
                && OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Otis.AutomatycznieOdwierzajBilans))
            {
                GlobalTools.OtisTools.GetBilans();
            }
            if (BuildHelper.Work.Short.ShortForm.Instance != null)
            {
                try
                {
                    if (!BuildHelper.Work.Short.ShortForm.Instance.TopMost)
                        BuildHelper.Work.Short.ShortForm.Instance.TopMost = true;
                }
                catch { }
            }
        }

        #endregion

        #region private impl
        void OptionCache_OptionChanged(object optionId)
        {
            if (Init.InitFormOptionNames.Rozne_Group.Alerty.NieChowajErrorow.IsTheSameKey(optionId))
            {
                NieChowajErrorow = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Alerty.NieChowajErrorow);
            }
            else if (Init.InitFormOptionNames.Rozne_Group.Alerty.NieChowajWarningow.IsTheSameKey(optionId))
            {
                NieChowajWarningow = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Alerty.NieChowajWarningow);
            }
            else if (Init.InitFormOptionNames.Rozne_Group.Alerty.ChowajAutomatycznie.IsTheSameKey(optionId))
            {
                ChowajAlerty = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Alerty.ChowajAutomatycznie);
            }
            else if (OptionCache.IsTheSameId(optionId, Init.InitFormOptionNames.Rozne_Group.Alerty.CzasAlertu))
            {
                alert.AutoFormDelay = 1000 * OptionCache.GetOptionValue(optionId).AsInt(1);
            }
            else if (OptionCache.IsTheSameId(optionId, Init.InitFormOptionNames.Brancze.ActiveBranczDrive))
            {
                if (OldGlobalDrive.IsNotNull())
                    BranczeTools.UnSubstDrive(OldGlobalDrive);

                string drive = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Brancze.ActiveBranczDrive);
                OldGlobalDrive = drive;

                string dir = BranczeTools.ActiveBranczDir;

                if (drive.IsNotNull() && dir.IsNotNull())
                    BranczeTools.SubstDrive(drive, dir);
            }
            else if (OptionCache.IsTheSameId(optionId, Init.InitFormOptionNames.Brancze.TypNdrive))
            {
                BranczeTools.SetEnvVariables();
            }

            #region otis
            #region visibility
            
            

            if (optionId.IsNull() ||
                Init.InitFormOptionNames.Rozne_Group.Otis.PokazPasekOtisa.IsTheSameKey(optionId) ||
                Init.InitFormOptionNames.Rozne_Group.Otis.IntegrujZeStatusBarem.IsTheSameKey(optionId))
            {
                barOtis.Visible = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Otis.PokazPasekOtisa) &&
                    !OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Otis.IntegrujZeStatusBarem);
            }

            if (optionId.IsNull() || Init.InitFormOptionNames.Rozne_Group.Otis.PokazPasekOtisa.IsTheSameKey(optionId))
            {
                bool v = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Otis.PokazPasekOtisa);
                foreach (LinkPersistInfo link in barOtis.LinksPersistInfo)
                {
                    if (v)
                        link.Item.Visibility = BarItemVisibility.Always;
                    else
                        link.Item.Visibility = BarItemVisibility.Never;
                }
            }
            #endregion
            #region nazwy
            if (optionId.IsNull() || 
                Init.InitFormOptionNames.Rozne_Group.Otis.WyswietlajNazwy.IsTheSameKey(optionId) ||
                Init.InitFormOptionNames.Rozne_Group.Otis.IntegrujZeStatusBarem.IsTheSameKey(optionId) ||
                Init.InitFormOptionNames.Rozne_Group.StatusBar.WyswietlajNazwy.IsTheSameKey(optionId))
            {
                bool w = false;
                if(OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Otis.IntegrujZeStatusBarem))
                    w = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.StatusBar.WyswietlajNazwy);
                else
                    w = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Otis.WyswietlajNazwy);
                foreach (LinkPersistInfo link in barOtis.LinksPersistInfo)
                {
                    if (link.Item is BarEditItem)
                    {
                        link.Item.PaintStyle = (w ? BarItemPaintStyle.Caption : BarItemPaintStyle.Standard);
                        if (w)
                        {
                            if (!link.Item.Caption.EndsWith(":"))
                                link.Item.Caption += ":";
                            link.Item.Hint = "";
                        }
                        else
                        {
                            if (link.Item.Caption.EndsWith(":"))
                               link.Item.Caption = link.Item.Caption.TrimEnd(':');
                            link.Item.Hint = link.Item.Caption;
                        }
                    }
                }
            }
            #endregion

            #region integrowanie /merge
            if (optionId.IsNull() || 
                Init.InitFormOptionNames.Rozne_Group.Otis.IntegrujZeStatusBarem.IsTheSameKey(optionId))
            {
                ((System.ComponentModel.ISupportInitialize)(this.barManager1)).BeginInit();
                if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Otis.IntegrujZeStatusBarem))
                {
                    LinkPersistInfo torem = null;
                    foreach (LinkPersistInfo link in barOtis.LinksPersistInfo)
                    {
                        torem = null;
                        foreach (LinkPersistInfo l in statusBar.LinksPersistInfo)
                        {
                            if (l.Item.Name == link.Item.Name)
                            {
                                torem = l;
                                break;
                            }
                        }
                        if (torem == null)
                        {
                            torem = new LinkPersistInfo(link.Item);
                            torem.BeginGroup = link.BeginGroup;
                            statusBar.LinksPersistInfo.Add(torem);
                        }
                    }
                }
                else
                {
                    LinkPersistInfo torem = null;
                    foreach (LinkPersistInfo link in barOtis.LinksPersistInfo)
                    {
                        torem = null;
                        foreach (LinkPersistInfo l in statusBar.LinksPersistInfo)
                        {
                            if (l.Item.Name == link.Item.Name)
                            {
                                torem = l;
                                break;
                            }
                        }
                        if (torem != null)
                            statusBar.LinksPersistInfo.Remove(torem);
                    }
                }
                ((System.ComponentModel.ISupportInitialize)(this.barManager1)).EndInit();
            }
            #endregion
            if (optionId.IsNull() || Init.InitFormOptionNames.Rozne_Group.StatusBar.WyswietlajNazwy.IsTheSameKey(optionId))
            {
                bool w = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.StatusBar.WyswietlajNazwy);
                foreach (LinkPersistInfo link in statusBar.LinksPersistInfo)
                {
                    if (link.Item is BarEditItem)
                    {
                        link.Item.PaintStyle = (w ? BarItemPaintStyle.Caption : BarItemPaintStyle.Standard);
                        if (w)
                        {
                            if (!link.Item.Caption.EndsWith(":"))
                                link.Item.Caption += ":";
                            link.Item.Hint = "";
                        }
                        else
                        {
                            if (link.Item.Caption.EndsWith(":"))
                                link.Item.Caption = link.Item.Caption.TrimEnd(':');
                            link.Item.Hint = link.Item.Caption;
                        }
                    }
                }
            }
            #endregion
        }

        void Tools_ActiveBranchChanged(object sender, EventArgs e)
        {
            beiAktywnyBrancz.EditValue = Setup.Brancze.BranczeTools.ActiveBranch;
            bbiUpdateCurrentBrancz.Caption = "Aktualny Brancz";
            if (Setup.Brancze.BranczeTools.ActiveBranch.IsNotNull())
                bbiUpdateCurrentBrancz.Caption += " (" + Setup.Brancze.BranczeTools.ActiveBranch + ")";
        }
        private void OpenBrowserForm<T>(object browserId, bool allowNew = true)
        {
            ObjectDialogResult res = BrowserCache.ShowBrowserDialog(browserId, allowNew);
            if (res.DialogResult == System.Windows.Forms.DialogResult.OK)
            {
                if (res.Value == null)
                    mdiHelper.GetMdiChildFull(typeof(T), MdiOptions.DefaultNoRemember);
                else
                    mdiHelper.GetMdiChild(typeof(T), res.Value);
            }
        }

        private object GetValueFromBrowser(object browserId, bool allowNew = false ,string caption = "")
        {
            Browser b;
            if (caption.IsNull())
                b = BrowserCache.GetBrowser(browserId, false);
            else
            {
                b = BrowserCache.GetBrowser(browserId, true);
                b.Caption = caption;
            }
            ObjectDialogResult dlg = b.ShowDialog(null, allowNew);
            if (dlg.DialogResult == System.Windows.Forms.DialogResult.OK)
                return dlg.Value;
            if (allowNew)
                return BrowserCancel;
            return null;
        }

        private void mdiHelper_FormCreated(object sender, FormCreateEventArgs e)
        {
            e.Form.FormClosing += new FormClosingEventHandler(Form_FormClosing);
        }

        void Form_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.MdiFormClosing)
                e.Cancel = true;
            else if (e.CloseReason == CloseReason.ApplicationExitCall ||
                e.CloseReason == CloseReason.TaskManagerClosing ||
                e.CloseReason == CloseReason.WindowsShutDown)
                Program.IsExit = true;
        }
        #endregion

        #region Plik
        public override void HideToTray()
        {
            base.HideToTray();
            bbiPokaz.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
            bbiSchowaj.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
        }
        public override void ShowFromTray()
        {
            base.ShowFromTray();
            bbiPokaz.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            bbiSchowaj.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
        }
        private void bbiPokaz_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowFromTray();
        }

        private void bbiSchowaj_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            HideToTray();
        }

        private void bbiZamknij_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Close();
        }
       
        private void bbiZamknijWszystkieAlerty_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            CloseAllAlerts();
        }

        private void bbiNaSkroty_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Work.Short.ShortForm.ShowForm();
        }

        private void notifyIcon1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                popupMenu1.ShowPopup(Control.MousePosition);
            }
        }
        #endregion

        #region Pomoc
        private void bbiKontakt_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (KontaktTools.IsServer)
            {
                if (KontaktUsersForm.Instance != null)
                {
                    User32.SetForegroundWindow(KontaktUsersForm.Instance.Handle);
                }
                else
                {
                    KontaktUsersForm f = new KontaktUsersForm(ServerNew.Instance.MyClient);
                    f.Show(this);
                }

                //if (KontaktUsersFormNew.Instance != null)
                //{
                //    User32.SetForegroundWindow(KontaktUsersFormNew.Instance.Handle);
                //}
                //else
                //{
                //    KontaktUsersFormNew f = new KontaktUsersFormNew(Server.Instance.OwnerClinet);
                //    f.Show(this);
                //}
            }
            else
            {
                //Client.Instance.Form.ConnectWithUser(KontaktTools.ServerName, KontaktTools.ServerName);
                if (ClientNew.Instance != null)
                    ClientNew.Instance.Form.ConnectWithUser(KontaktTools.ServerName);
            }
        }
       
        #endregion

        #region Definicje
        private void bbiProjekty_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper.GetMdiChild<Setup.Apps.FormProjekty>();
        }

        private void bbiSrodowiska_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper.GetMdiChild<Setup.Srodowiska.FormSrodowiska>();
        }

        private void bbiBazyDanych_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper.GetMdiChild<Setup.BazyDanych.FormBazyDanych>();
        }
        private void bbiSerwery_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            OpenBrowserForm<Setup.Serwery.SerweryForm>(Init.InitFormBrowserNames.Setup.Serwery);
        }

        private void bbiGrupyPlikow_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper.GetMdiChild<Setup.Pliki.FormPliki>();
        }
        private void bbiBrancze_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            OpenBrowserForm<Setup.Brancze.FormBrancz>(Init.InitFormBrowserNames.Setup.Brancze);
        }
        private void bbiKonfigiBudowaniaGui_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper.GetMdiChild<Setup.Konfigi.FormKonfigi>();
        }
        private void bbiVisualStudio_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper.GetMdiChild<Setup.VisualStudio.FormVS>();
        }

        #region Szablony
        private void bbiSzablonyGui_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            OpenBrowserForm<Work.Template.GuiTemplateForm>(Init.InitFormBrowserNames.Setup_Group.Template.Gui);
        }

        private void bbiSzblonyJava_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            OpenBrowserForm<Work.Template.JavaTemplateForm>(Init.InitFormBrowserNames.Setup_Group.Template.Java);
        }
        #endregion
        #endregion

        #region Ustaiwenia
        private void bbiOpcje_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper.GetMdiChild<Setup.Opcje.FormOpcje>();
        }
        private void bbiWyglad_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ProgNetComponentsDx.Forms.FormSkinChooser.ShowSkinChooserDialog() == System.Windows.Forms.DialogResult.OK)
            {
                OptionCache.SetOptionValue(Init.InitFormOptionNames.Rozne.Skorka, LookAndFeel.ActiveSkinName, true);
                OptionCache.SetOptionValue(Init.InitFormOptionNames.Rozne.Styl, LookAndFeel.ActiveStyle.ToString(), true);
            }
        }

        #endregion

        #region status bar
        private void repItemAktualnyBrancz_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            ObjectDialogResult res = BrowserCache.ShowBrowserDialog(Init.InitFormBrowserNames.Setup.Brancze);
            if (res.DialogResult == System.Windows.Forms.DialogResult.OK)
            {
                Setup.Brancze.BranczeTools.ActiveBranch = res.Value.AsString();
            }
        }
        private void repItemDefServer_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Delete)
            {
                beiDefServer.EditValue = null;
            }
            else if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph)
            {
                if (beiDefServer.EditValue.IsNotNull())
                {
                    GlobalTools.ServerTools.RunServer(beiDefServer.EditValue.AsInt(), BranczeTools.ActiveBranch,
                        OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Narzedzia.SerwerBringToFront), 
                        GlobalTools.ServerTools.ServerRestartType.Ask);
                }
                else
                {
                    this.ShowDxInfoDialog("Wybierz server");
                }
            }
        }

        private void beiDefServer_EditValueChanged(object sender, EventArgs e)
        {
            OptionCache.SetOptionValue(Init.InitFormOptionNames.Rozne_Group.StatusBar.DefServer, beiDefServer.EditValue);
        }

        #endregion

        #region budowanie
        private void bbiBudowanieGui_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string brancz = "";
            if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Work_Group.Gui.AllowMulti))
            {
                object obj = GetValueFromBrowser(Init.InitFormBrowserNames.Setup.Brancze, true);
                if (obj == BrowserCancel)
                    return;
                brancz = obj.AsString();
                if (brancz.IsNotNull())
                    mdiHelper.GetMdiChild<Work.GUI.BudowanieGui>(brancz);
                else
                    mdiHelper.GetMdiChild<Work.GUI.BudowanieGui>();
            }
            else
            {
                mdiHelper.GetMdiChild<Work.GUI.BudowanieGui>();
            }
        }

        private void bbiBudowanieJava_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string brancz = "";
            if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Work_Group.Java.AllowMulti))
            {
                object obj = GetValueFromBrowser(Init.InitFormBrowserNames.Setup.Brancze, true);
                if (obj == BrowserCancel)
                    return;
                brancz = obj.AsString();
                if (brancz.IsNotNull())
                    mdiHelper.GetMdiChild<Work.JAVA.BudowanieJavy>(brancz);
                else
                    mdiHelper.GetMdiChild<Work.JAVA.BudowanieJavy>();
            }
            else
            {
                mdiHelper.GetMdiChild<Work.JAVA.BudowanieJavy>();
            }
        }
        #endregion

        #region Narzedzia
        private void bbiAutoCodeReview_ItemClick(object sender, ItemClickEventArgs e)
        {
            //ProgNetComponents.Wcf.AppUpdate.BaseAppUpdater u = new ProgNetComponents.Wcf.AppUpdate.BaseAppUpdater();
            //u.Version = "4.5.5.0";
            //u.ZipFile = @"\\pcplukom-1\ProgNet Instalki\BuildHelper_install.exe";
            //u.RunableName = "BuildHelper.exe";
            //u.AppName = Application.ProductName;
            //u.AppDirectory = Application.StartupPath;
            //string tmpFile = System.IO.Path.GetTempFileName();
            //string appUpdater = System.IO.Path.Combine( System.IO.Path.GetTempPath() , "AppUpdater.exe");
            //u.ToString().WriteToFile(tmpFile);
            //System.IO.File.WriteAllBytes(appUpdater, Properties.Resources.AppUpdater);
            //System.IO.File.Copy(Application.StartupPath + "\\ProgNetComponents.dll", System.IO.Path.Combine(System.IO.Path.GetTempPath(), "ProgNetComponents.dll"), true);
            
            //Process.Start(appUpdater, tmpFile.AddDoubleQuotes());
            
            //Application.Exit();

            BuildHelper.Work.Tools.Forms.CodeReview rw = new Work.Tools.Forms.CodeReview();
            rw.Show();
        }

        private void bbiUruchomSerwer_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            object obj = GetValueFromBrowser(Init.InitFormBrowserNames.Setup.Serwery);
            if (obj!=null)
                GlobalTools.ServerTools.RunServer(obj.AsInt(), BranczeTools.ActiveBranch, OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Narzedzia.SerwerBringToFront));
        }
        #region Internal SDK
        private Process InternalSdkProcess = null;
        private FormBackGroundWorkSingleThread InternalSdkForm;

        private void bbiNarzedziaPobierzInternalSdk_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string brancz = BranczeTools.ActiveBranch;
            GetInternalSdk(brancz);
        }

        private void bbiNarzedziaSdkBrancz_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (InternalSdkProcess == null)
            {
                string brancz = this.GetValueFromBrowser(Init.InitFormBrowserNames.Setup.Brancze).AsString();
                GetInternalSdk(brancz);
            }
            else
            {
                this.ShowDxInfoDialog("Operacja w toku.");
            }
        }
        private void bbiInternalSdkForOtherBrancz_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (InternalSdkProcess == null)
            {
                InternalSdkHelp h = new InternalSdkHelp();
                h.SvnBranczForInternalSdk = this.GetValueFromBrowser(Init.InitFormBrowserNames.Statyczne.BranczeSVN, false, "Brancz dla Internal SDK").AsString();
                h.LocalForExtract = this.GetValueFromBrowser(Init.InitFormBrowserNames.Setup.Brancze, false, "Brancz do rozpakowania").AsString();
                
                GetInternalSdk(h);
            }
            else
            {
                this.ShowDxInfoDialog("Operacja w toku.");
            }
        }

        private class InternalSdkHelp
        {
            public string SvnBranczForInternalSdk
            {
                get;
                set;
            }
            public string LocalForExtract
            {
                get;
                set;
            }
        }
        public void GetInternalSdk(string brancz)
        {
            DataRow r = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Setup.Brancze, brancz);
            string svnBrancz = brancz;
            if (r != null)
            {
                svnBrancz = r["STP_BR_SVN"].AsString();
            }
            GetInternalSdk(new InternalSdkHelp { LocalForExtract = brancz, SvnBranczForInternalSdk = svnBrancz });
        }
        private void GetInternalSdk(InternalSdkHelp brancze)
        {
            if (InternalSdkProcess == null)
            {
                if (brancze.LocalForExtract.IsNotNull() && brancze.SvnBranczForInternalSdk.IsNotNull())
                {
                    InternalSdkProcess = GlobalTools.CreateCMDProcess(InternalSdk_Data);
                    InternalSdkForm = new FormBackGroundWorkSingleThread();
                    InternalSdkForm.BackgroundControl.ProgressType = ProgressType.Merque;
                    InternalSdkForm.Text = "Pobieranie Internal SDK z " + brancze.SvnBranczForInternalSdk + " do " + brancze.LocalForExtract;
                    InternalSdkForm.DoWork += new DoWorkEventHandler(f_DoWork);
                    InternalSdkForm.BackgroundControl.SupportCancelation = true;
                    InternalSdkForm.Argument = brancze;
                    InternalSdkForm.ShowDialog();
                }
                else
                {
                    this.ShowDxErrorDialog("Brak Brancza.");
                }
            }
            else
            {
                this.ShowDxInfoDialog("Operacja w toku.");
            }
            
        }
        private void f_DoWork(object sender, DoWorkEventArgs e)
        {
            InternalSdkHelp h = e.Argument as InternalSdkHelp;
            GlobalTools.FilesTools.GetBestInternalSdk(InternalSdkProcess, h.SvnBranczForInternalSdk, h.LocalForExtract);
            while (InternalSdkProcess != null)
            {
                Application.DoEvents();
                if (Program.IsExit)
                    return;
            }
        }
        private void InternalSdk_Data(object sender, DataReceivedEventArgs e)
        {
            string str = e.Data.AsString();
            if (InternalSdkForm == null)
                return;
            if (!str.XMatch("echo"))
            {
                InternalSdkForm.BackgroundControl.LabelText = str;
            }
            bool finish = false;
            if (str.XMatch("^" + GlobalTools.Messages.MSG_ERROR) || str.XMatch("The process cannot access the file because it is being used by another process"))
            {
                finish = true;
                ShowErrorAlert(str);
            }
            if (str.XMatch("^" + GlobalTools.Messages.MSG_WARNING))
            {
                finish = true;
                ShowWarningAlert(str);
            }
            if (str.XMatch("^" + GlobalTools.Messages.MSG_INFO))
            {
                InternalSdkForm.BackgroundControl.Label2Text = str.XReplace(GlobalTools.Messages.MSG_INFO, "");
            }
            if (str == GlobalTools.FilesTools.MSG_KONIEC_POBIERANIA)
            {
                finish = true;
            }
            if (InternalSdkForm.BackgroundControl.IsCanceling)
                finish = true;

            if (finish)
            {
                try
                {
                    InternalSdkProcess.KillProcessTree();
                    InternalSdkProcess.Dispose();
                }
                catch { }
                InternalSdkProcess = null;
                try
                {
                    InternalSdkForm.Close();
                }
                catch { }
                InternalSdkForm = null;
            }
        }
        #endregion

        #region Bazy Danych
        private void bbiZmienBazeDanych_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (DbChangeProcess == null)
            {
                object server = GetValueFromBrowser(Init.InitFormBrowserNames.Setup.Serwery);
                if (server != null)
                {
                    ZmienBazeDlaServera(server.AsInt(-1));
                }
            }
            else
            {
                this.ShowDxInfoDialog("Operacja w toku.");
            }
        }

        private void bbiZmienBazeDanychDlaDomyslnegoServera_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (DbChangeProcess == null)
            {
                if (beiDefServer.EditValue.IsNotNull())
                {
                    ZmienBazeDlaServera(beiDefServer.EditValue.AsInt(-1));
                }
                else
                {
                    this.ShowDxInfoDialog("Wybierz domyślny serwer.");
                }
            }
            else
            {
                this.ShowDxInfoDialog("Operacja w toku.");
            }
        }

        private void ZmienBazeDlaServera(int server)
        {
            DataRow r = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Setup.Serwery, server);
            if (r != null)
            {
                object baza = GetValueFromBrowser(Init.InitFormBrowserNames.Setup.BazyDanych);
                if (baza != null)
                {
                    string typ = r["STP_SRW_TYP"].AsString();
                    bool restart = false;
                    bool isRunning = GlobalTools.ServerTools.IsServerRunning(server.AsInt());
                    switch (typ)
                    {
                        case GlobalTools.ServerTools.ServerType.OAS:
                            if (!isRunning)
                            {
                                if (this.ShowDxYNQuestionDialog("Serwer musi być uruchomiony aby zmienić Bazę Danych.\nCzy chcesz uruchomić serwer?") == System.Windows.Forms.DialogResult.Yes)
                                {
                                    GlobalTools.ServerTools.RunServer(server.AsInt(), BranczeTools.ActiveBranch, OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Narzedzia.SerwerBringToFront), GlobalTools.ServerTools.ServerRestartType.Ask);
                                    return;
                                }
                            }
                            break;
                        case GlobalTools.ServerTools.ServerType.JBoss4:
                        case GlobalTools.ServerTools.ServerType.JBoss5:
                            if (isRunning)
                                restart = true;
                            break;
                        default:
                            this.ShowDxInfoDialog("Serwer nie jest wspierany.");
                            return;
                    }
                    DbChangeProcess = GlobalTools.CreateCMDProcess(DbChangeProcess_Data);
                    GlobalTools.ServerTools.ChangeDataSource(DbChangeProcess, server, baza.AsInt(-1));
                    if(restart)
                        GlobalTools.ServerTools.RunServer(server.AsInt(), BranczeTools.ActiveBranch, OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Narzedzia.SerwerBringToFront), GlobalTools.ServerTools.ServerRestartType.Restart);
                                
                }
            }
        }

        private void DbChangeProcess_Data(object sender, DataReceivedEventArgs e)
        {
            string str = e.Data.AsString();
            if (str.StartsWith(GlobalTools.ServerTools.MSG_DATA_SOURCE_ZMIENIONY))
            {
                Dictionary<int, string> data = str.GetFirstMatch("user:(.*); pass:(.*); url:(.*)", new int[] { 1, 2, 3 });

                ShowInfoAlert("DataSource Zmieniony.".AppendLine("user: " + data[1]).AppendLine("pass: " + data[2]).AppendLine("url:  " + data[3]));
                try
                {
                    DbChangeProcess.KillProcessTree();
                    DbChangeProcess.Dispose();
                }
                catch { }
                DbChangeProcess = null;
            }
            else if (str.XMatch("^" + GlobalTools.Messages.MSG_ERROR))
            {
                ShowErrorAlert("DataSource nie zmieniony!\n" + str.XReplace("^" + GlobalTools.Messages.MSG_ERROR, ""));
                try
                {
                    DbChangeProcess.KillProcessTree();
                    DbChangeProcess.Dispose();
                }
                catch { }
                DbChangeProcess = null;
            }
        }

        #endregion

        private void bbiOtworzBazeDanych_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            object db = GetValueFromBrowser(Init.InitFormBrowserNames.Setup.BazyDanych);
            if (db.IsNotNull())
            {
                DataRow r = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Setup.BazyDanych, db);
                Setup.BazyDanych.Tools.OpenDB(r);
            }
        }
        private void bbiNarzedziaOtworzSrodowisko_ItemClick(object sender, ItemClickEventArgs e)
        {
            object id = GetValueFromBrowser(Init.InitFormBrowserNames.Setup.Srodowiska);
            if (id.IsNotNull())
            {
                DataRow r = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Setup.Srodowiska, id);
                string envName = r["STP_SR_NAZWA"].AsString();
                string msg = "Otwieranie " + envName;
                AlertInfo i = new AlertInfo();
                i.Id = msg;
                i.ShouldStay = true;

                ShowAlert(msg, commonImageCollectionFull1.Images[83], new AlertInfo(true, Setup.Srodowiska.Tools.GetOnenId(envName)));
                Setup.Srodowiska.Tools.OpenUrl(r);
            }
        }

        private void bbiOpenConsole_ItemClick(object sender, ItemClickEventArgs e)
        {
            object id = GetValueFromBrowser(Init.InitFormBrowserNames.Setup.Srodowiska);
            if (id.IsNotNull())
            {
                DataRow r = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Setup.Srodowiska, id);
                string envName = r["STP_SR_NAZWA"].AsString();
                string host = r["STP_SR_HOST"].AsString();
                string msg = "Otwieranie " + envName + " (" + host + ")";

                ShowAlert(msg, commonImageCollectionFull1.Images[14], new AlertInfo(true, Setup.Srodowiska.Tools.GetOnenConsoleId(envName)));
                Setup.Srodowiska.Tools.OpenConsole(r);
            }
        }

        private void bbiUpdateEnv_ItemClick(object sender, ItemClickEventArgs e)
        {
            object id = GetValueFromBrowser(Init.InitFormBrowserNames.Setup.Srodowiska);
            if (id.IsNotNull())
            {
                DataRow r = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Setup.Srodowiska, id);
                string envName = r["STP_SR_NAZWA"].AsString();
                string msg = "Uaktualnianie " + envName;

                ShowAlert(msg, commonImageCollectionFull1.Images[86], new AlertInfo(true, Setup.Srodowiska.Tools.GetUpdateEnvId(envName)));
                Setup.Srodowiska.Tools.UpdateEnv(envName);
            }
        }

        private void bbiUpdateAllEnvs_ItemClick(object sender, ItemClickEventArgs e)
        {
            Setup.Srodowiska.Tools.UpdateAllEnvs(true, null);
        }

        private void bbiToolsUpdateDb_ItemClick(object sender, ItemClickEventArgs e)
        {
            object id = GetValueFromBrowser(Init.InitFormBrowserNames.Setup.Srodowiska);
            if (id.IsNotNull())
            {
                DataRow r = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Setup.Srodowiska, id);
                string envName = r["STP_SR_NAZWA"].AsString();
                string msg = "Uaktualnianie Bazy Danych " + envName;

                ShowAlert(msg, commonImageCollectionFull1.Images[86], new AlertInfo(true, Setup.BazyDanych.Tools.GetUpdateDbId(envName)));
                Setup.BazyDanych.Tools.UpdateDb(envName);
            }
        }

        private void bbiToolsUpdateAllDb_ItemClick(object sender, ItemClickEventArgs e)
        {
            //Setup.BazyDanych.Tools.UpdateAllDb(true, null);
            BHTasks.DbUpdateTask.UpdateAll();
        }

        private void bbiUpdateBrancz_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (GlobalTools.TortoiseTools.CheckTortoiseProc())
            {
                string brancz = GetValueFromBrowser(Init.InitFormBrowserNames.Setup.Brancze).AsString();
                if (brancz.IsNotNull())
                    GlobalTools.TortoiseTools.TortoiseProcUpdate(brancz, null);
            }
        }

        private void bbiUpdateCurrentBrancz_ItemClick(object sender, ItemClickEventArgs e)
        {
            string brancz = GetActiveBrancz();
            if (brancz.IsNotNull())
                GlobalTools.TortoiseTools.TortoiseProcUpdate(brancz, null);
        }

        private void bbiTortoiseCommit_ItemClick(object sender, ItemClickEventArgs e)
        {
            string brancz = GetValueFromBrowser(Init.InitFormBrowserNames.Setup.BranczeAktywne).AsString();
            if (brancz.IsNotNull())
                GlobalTools.TortoiseTools.Commit(brancz); 
        }

        private void bbiTortoiseCommitCurrent_ItemClick(object sender, ItemClickEventArgs e)
        {
            GlobalTools.TortoiseTools.Commit(BranczeTools.ActiveBranch);
        }

        private void bbiFixDataSet_ItemClick(object sender, ItemClickEventArgs e)
        {
            Work.Tools.DataSetFix.DataSetFixTools.ShowFixDataSetDialog();
        }
        #endregion

        #region Work
        private void bbiTortoiseSvn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper.GetMdiChild<Work.Tortoise.TortoiseForm>();
        }
        private void bbiSecurity_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper.GetMdiChild<Work.Tools.SecurityCheckForm>();
            //mdiHelper.GetMdiChild<Work.Tools.SecurityFileCheckForm>();
        }
        private void bbiOperacjeNAPlikach_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper.GetMdiChild<Work.OperacjeNaPlikach.OperacjeNaPlikachForm>();
        }
        private void bbiGenerator_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper.GetMdiChild<Work.Tools.GeneratorForm>();
        }
        private void bbiScriptCompare_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.mdiHelper.GetMdiChild<Work.Tools.ScriptCompare.CompareForm>();
        } 

        #endregion

        private void bbiZmienneSrodowiskowe_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper.GetMdiChild<Narzedzia.ZmienneSrodowiskowe.FormZmienneSrodowiskowe>();
        }
       
        #region Otis
        private bool lockOtis = false;
        public void SetLoginTime(string logInTime, string brakeTime, string bilans, bool startTimer)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string, string, string, bool>(SetLoginTime), logInTime, brakeTime, bilans, startTimer);
                return;
            }

            beiOtisBilans.EditValue = bilans;
            if (logInTime.IsNull())
            {
                StopOtisTimer();
                lockOtis = true;
                beiOtisCzasPrzyjscia.EditValue = null;
                beiOtisPrzerwy.EditValue = null;
                beiOtisGodzinaWyjscia.EditValue = null;
                beiOtisPozostalo.EditValue = null;
                lockOtis = false;
                return;
            }
            
            lockOtis = true;
            bool modified = false;
            long logInSec = GetSeconds(logInTime);
            long brakeSec = GetSeconds(brakeTime);
            if (beiOtisCzasPrzyjscia.EditValue.IsNull() || beiOtisCzasPrzyjscia.EditValue.AsLong() != logInSec)
            {
                beiOtisCzasPrzyjscia.EditValue = logInSec;
                modified = true;
            }
            if (beiOtisPrzerwy.EditValue.AsLong() != brakeSec)
            {
                if (beiOtisPrzerwy.EditValue.AsLong() < brakeSec || modified)
                {
                    beiOtisPrzerwy.EditValue = brakeSec;
                    modified = true;
                }
            }
            if (beiOtisPozadany.EditValue.IsNull())
            {
                string pozadany = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Rozne_Group.Otis.CzasPracy);
                if (pozadany.IsNull())
                    pozadany = "8:00";

                beiOtisPozadany.EditValue = GetSeconds(pozadany);
                modified = true;
            }
            
            if (modified)
            {
                if (!setFromGodzina)
                    SetGodzinaWyjscia();
                else
                    SetPozadany();

                if (startTimer && beiOtisGodzinaWyjscia.EditValue.AsInt() > GetSeconds(DateTime.Now))
                    StartOtisTimer();
            }
            lockOtis = false;
        }

        private void SetPozadany()
        {
            long cwy = beiOtisGodzinaWyjscia.EditValue.AsLong();
            long cwe = beiOtisCzasPrzyjscia.EditValue.AsLong();
           
            lockOtis = true;
            if (cwy > cwe)
            {
                long cb = beiOtisPrzerwy.EditValue.AsLong();
                long clunch = GetSeconds(OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Rozne_Group.Otis.Lunch));
                long cp = cwy - cwe - cb;
                long h6 = 6 * 60 * 60;
                if (cb < clunch && cp > h6)
                {
                    cp -= (clunch - cb);
                    cp = Math.Max(h6, cp);
                }
                beiOtisPozadany.EditValue = cp;
            }
            lockOtis = false;
        }

        internal void SetBilans(string bilans)
        {
            if (this.IsDisposed || this.Disposing)
                return;
            if (this.InvokeRequired)
            {
                if (this.IsDisposed || this.Disposing || !this.IsHandleCreated)
                    return;
                try
                {
                    this.Invoke(new Action<string>(SetBilans), bilans);
                }
                catch { }
                return;
            }
            beiOtisBilans.EditValue = bilans;
        }
        private void SetGodzinaWyjscia()
        {
            long cp = beiOtisPozadany.EditValue.AsLong();
            long cwe = beiOtisCzasPrzyjscia.EditValue.AsLong();
            long cb = beiOtisPrzerwy.EditValue.AsLong();
            long cwy = cwe + cp;
            long clunch = 0;
            if (cp > 6 * 60 * 60)//6h
            {
                clunch = GetSeconds(OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Rozne_Group.Otis.Lunch));
            }
            
            if (cb > clunch)
                cwy += cb;
            else
                cwy += clunch;
            lockOtis = true;
            beiOtisGodzinaWyjscia.EditValue = cwy;
            lockOtis = false;
        }

        static string TIME_MASK = "(\\d*):(\\d*):?(\\d*)";

        private long GetSeconds(string time)
        {
            long h = time.GetFirstMatch(TIME_MASK, 1).AsInt();
            long m = time.GetFirstMatch(TIME_MASK, 2).AsInt();
            long s = time.GetFirstMatch(TIME_MASK, 3).AsInt();
            return s + m * 60 + h * 60 * 60;
        }
        private long GetSeconds(TimeSpan dt)
        {
            return (long)(dt.Seconds + dt.Minutes * 60 + dt.Hours * 60 * 60);
        }
        private long GetSeconds(DateTime dt)
        {
            return (long)(dt.Second + dt.Minute * 60 + dt.Hour * 60 * 60);
        }
        private string GetTime(long seconds)
        {
            long h = seconds / (60 * 60);
            long m = (seconds - (h * 60 * 60)) / 60;
            long s = (seconds - (h * 60 * 60) - (m * 60));
            return h.ToString() + ":" + (m > 9 ? "" : "0") + m.ToString() +":"+ (s > 9 ? "" : "0") + s.ToString();
        }

        private void repItemCzasPrzyjscia_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Tag.AsString() == "S")
            {
                GlobalTools.OtisTools.SprawdzOtis(false);
            }
        }

        bool otisTimerStarted = false;
        bool setFromGodzina = false;
        private void StartOtisTimer()
        {
            if (otisTimerStarted)
                return;
            if (beiOtisCzasPrzyjscia.EditValue.IsNotNull() &&
                beiOtisPozadany.EditValue.IsNotNull())
            {
                otisTimerStarted = true;
                bbiOdliczaj.Caption = "Zatrzymaj";
                timerOtis.Start();
            }
        }

        private void StopOtisTimer()
        {
            if (!otisTimerStarted)
                return;
            
            beiOtisPozostalo.EditValue = null;
            otisTimerStarted = false;
            bbiOdliczaj.Caption = "Odliczaj";
            timerOtis.Stop();
        }

        private void timerOtis_Tick(object sender, EventArgs e)
        {
            if (beiOtisCzasPrzyjscia.EditValue.IsNotNull())
            {
                long cwy = beiOtisGodzinaWyjscia.EditValue.AsLong();
                long ct = GetSeconds(DateTime.Now);
                long cp = cwy - ct;
                if (cp <= 0)
                {
                    StopOtisTimer();
                    lockOtis = true;
                    beiOtisCzasPrzyjscia.EditValue = null;
                    beiOtisPozostalo.EditValue = null;
                    lockOtis = false;
                    ShowAlert("Koniec pracy!\nWynocha do domu!", true, true, WarnImg);
                }
                else
                {
                    beiOtisPozostalo.EditValue = cp;
                }
            }
        }
       
        private void beiOtisCzasPrzyjscia_EditValueChanged(object sender, EventArgs e)
        {
            if (!lockOtis)
                SetGodzinaWyjscia();
        }

        private void beiOtisPozadany_EditValueChanged(object sender, EventArgs e)
        {
            if (!lockOtis)
            {
                setFromGodzina = false;
                SetGodzinaWyjscia();
            }
        }

        private void beiOtisPrzerwy_EditValueChanged(object sender, EventArgs e)
        {
            if (!lockOtis)
            {
                if (setFromGodzina)
                    SetPozadany();
                else
                    SetGodzinaWyjscia();
            }
        }

        private void beiOtisPozostalo_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void beiOtisGodzinaWyjscia_EditValueChanged(object sender, EventArgs e)
        {
            long cwy = beiOtisGodzinaWyjscia.EditValue.AsLong();
            long cwe = beiOtisCzasPrzyjscia.EditValue.AsLong();
            if (cwy < cwe)
            {
                beiOtisGodzinaWyjscia.EditValue = (cwe + 60);
                return;
            }
            if (!lockOtis)
            {
                setFromGodzina = true;
                SetPozadany();
            }
            else
            {
                setFromGodzina = false;
            }
        }

        private void bbiOdliczaj_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (otisTimerStarted)
                StopOtisTimer();
            else
                StartOtisTimer();
        }

        #endregion

        private void bbiZadania_ItemClick(object sender, ItemClickEventArgs e)
        {
            mdiHelper.GetMdiChildFull<Scheduler.SchedulerForm>(MdiOptions.Default);
        }

        private void bbiMultiTask_ItemClick(object sender, ItemClickEventArgs e)
        {
            mdiHelper.GetMdiChild<Scheduler.FormMultiTask>();
        }

        private void bbiDbUtils_ItemClick(object sender, ItemClickEventArgs e)
        {
            mdiHelper.GetMdiChild<Work.Tools.DBUtilsForm>();
        }

        private void bbiLokalizacjeOpcji_ItemClick(object sender, ItemClickEventArgs e)
        {
            mdiHelper.GetMdiChild<Setup.OptionsTabs.OptionsTabsForm>();
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == (Keys.A | Keys.Control | Keys.Shift))
            {
                mdiHelper.GetMdiChildFull<Admin.FormQuery>(MdiOptions.DefaultNoRemember);
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void bbiResetSerwera_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (Kontakt.KontaktTools.IsServer)
            {
                //if (Kontakt.Server.Instance != null)
                //{
                //    Kontakt.Server.Instance.Stop();
                //    Kontakt.Server.Instance.Run();
                //}
                    Kontakt.ServerNew.RestartServer();
            }
        }

        private void bbiStopSerwer_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (Kontakt.KontaktTools.IsServer)
            {
                Kontakt.ServerNew.StopServer();
            }
        }

        private void bbiWsCaller_ItemClick(object sender, ItemClickEventArgs e)
        {
            //BuildHelper.Work.Tools.Forms.CodeReview rw = new Work.Tools.Forms.CodeReview();
            //rw.Show();
            //mdiHelper.GetMdiChild<Admin.WsdlCaller>();
            //mdiHelper.GetMdiChild<Form1>();
        }

        private void barManager1_LayoutUpgrade(object sender, DevExpress.Utils.LayoutUpgadeEventArgs e)
        {
            barManager1.BeginInit();

            int ver = e.PreviousVersion.AsInt();
            if (ver < 2)
            {
                bbiBudowanieGui.BeginUpdate();
                bbiBudowanieGui.ImageIndex = 93;
                bbiBudowanieGui.EndUpdate();
                bbiBudowanieJava.BeginUpdate();
                bbiBudowanieJava.ImageIndex = 94;
                bbiBudowanieJava.EndUpdate();
            }
            if (ver < 3)
            {
                EnsureLink(bbiCustomBrowser, bsiDefinicje.LinksPersistInfo);
                EnsureLink(bbiAutoCodeReview, bsiNarzedzia.LinksPersistInfo);
            }
            if (ver <4)
            {
                EnsureLink(bbiScriptCompare, bsiWork.LinksPersistInfo);
            }
            if (ver < 5)
            {
                EnsureLink(bbiFixDataSet, bsiNarzedzia.LinksPersistInfo);
            }
            barManager1.EndInit();
        }
        private void EnsureLink(BarButtonItem item, LinksInfo links)
        {
            foreach (LinkPersistInfo link in links)
            {
                if (link.Item == item)
                {
                    link.Visible = true;
                    return;
                }
            }
            links.Add(new LinkPersistInfo(item));
        }

        private void bbiFaktura_ItemClick(object sender, ItemClickEventArgs e)
        {
            mdiHelper.GetMdiChild<BuildHelper.Setup.Faktury.Bills.FormBills>();
        }

        private void layoutProvider_LayoutLoaded(object sender, EventArgs e)
        {
            bar2.OptionsBar.DisableCustomization = false;
        }

        private void xtraTabbedMdiManager1_PageAdded(object sender, DevExpress.XtraTabbedMdi.MdiTabPageEventArgs e)
        {
            if(this.imageIndexes.ContainsKey(e.Page.MdiChild.GetType()))
                e.Page.ImageIndex = imageIndexes[e.Page.MdiChild.GetType()];
        }

        private void bbiCustomBrowser_ItemClick(object sender, ItemClickEventArgs e)
        {
            mdiHelper.GetMdiChild<Setup.ProcedurySql.CustomBrowsers.FormCustomBrowserAll>();
        }

        private void bbiProcedurySQL_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.OpenBrowserForm<Setup.ProcedurySql.FormProcedury>(Init.InitFormBrowserNames.Setup_Group.Sql.ProcedurySql);
        }

        private void bbiTypySql_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.mdiHelper.GetMdiChild<Work.Tools.Security.FormNewSecurity>();
            //this.mdiHelper.GetMdiChild<Setup.ProcedurySql.Typy.FormTypySQL>();
        }

        


    }

    public enum AlertType
    {
        Error,
        Info,
        Warn
    }
}
